package Concurrency2.Chapter06_AQS;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.AbstractQueuedSynchronizer;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;

/**
 * Instruction：使用AQS实现一个独占锁
 * Author：@author MaLi
 */
public class T02_AQSLock implements Lock {
    private static Sync sync = new Sync();

    @Override
    public void lock() {
//        sync.tryAcquire(1);  //注意, 这里不能直接调用Sync的tryAccquire方法, 否则tryAccquire获取锁失败, 就永远得不到锁了.
        sync.acquire(1);//AQS的模板方法
    }

    @Override
    public void unlock() {
//        sync.tryRelease(1);
        sync.release(1);//AQS的模板方法
    }

    //创建一个同步器内部类
    public static class Sync extends AbstractQueuedSynchronizer {

        //钩子函数: 尝试CAS设置state, 如果没有成功, 则acquireQueued添加到队列中
        // 逻辑: 抢占锁的钩子实现, 将锁状态设置为1, 表示互斥锁已经被占用, 并保存当前线程.
        @Override
        protected boolean tryAcquire(int arg) {
            if (compareAndSetState(0, 1)) {
                //设置独占锁的拥有者线程为当前线程
                setExclusiveOwnerThread(Thread.currentThread());
                return true;
            }
            return false;
        }

        @Override
        protected boolean tryRelease(int arg) {
            //合法性校验
            //如果当前线程不是占有锁的线程
            if (Thread.currentThread() != getExclusiveOwnerThread()) {
                throw new IllegalMonitorStateException();
            }
            //如果锁的状态是无占用状态
            if (getState() == 0) {
                throw new IllegalMonitorStateException();
            }
            setExclusiveOwnerThread(null);
            setState(0);
            return true;
        }
    }


    @Override
    public void lockInterruptibly() throws InterruptedException {

    }

    @Override
    public boolean tryLock() {
        return false;
    }

    @Override
    public boolean tryLock(long time, TimeUnit unit) throws InterruptedException {
        return false;
    }


    @Override
    public Condition newCondition() {
        return null;
    }

}
